package com.muchen.partnermatching.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author mu-chen
 * @create 2024-10-08 12:19
 * @Description
 */
//配置类
@Configuration
public class Corsconfig implements WebMvcConfigurer {
    //注入过滤器，这是为了解决跨域问题
    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowCredentials(true);
//        corsConfiguration.addAllowedOriginPattern("http://www.muchen-demo.cn");//允许哪些域访问
        corsConfiguration.addAllowedOriginPattern("http://localhost:5173");//允许哪些域访问
//        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");//请求的头字段
        corsConfiguration.addAllowedMethod("*");//请求的方式
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(source);
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedHeaders(CorsConfiguration.ALL)
                .allowedMethods(CorsConfiguration.ALL)
                .allowCredentials(true)
                .maxAge(3600);
    }
}
